<template>
  <div class="spec-preview">
    <img :src="skuImageList.length ? skuImageList[imgIndex].imgUrl : ''" />
    <!--  设置一个与外部容器区域同样大小的元素(用定位完成), 用于鼠标移动    -->
    <div class="event" @mousemove="handleMouseMove"></div>
    <div class="big">
      <img ref="bigImg" :src="skuImageList.length ? skuImageList[imgIndex].imgUrl : ''" />
    </div>
    <div class="mask" ref="mask"></div>
  </div>
</template>

<script>
  export default {
    name: "Zoom",
    props: ['skuImageList'],
    data(){
      return {
        imgIndex: 0
      }
    },

    mounted() {
      this.$bus.$on('getNewIndex', (index)=>{
        // console.log('传递的参数', index)
        this.imgIndex = index
      })
    },

    methods: {
      handleMouseMove(event){
        // console.log('滑动');
        let maskDom = this.$refs.mask;
        let bigImgDom = this.$refs.bigImg;



        // offsetX是指: 鼠标位置距离当前(鼠标所在)元素的左侧区域
        let leftPosition = event.offsetX - maskDom.offsetWidth/2
        let topPosition = event.offsetY - maskDom.offsetHeight/2;

        // 限制朦板移动的区域
        if (leftPosition <= 0) leftPosition = 0;
        // 由于在css中定义的: 朦板元素的宽高均为外层元素的一半。则左侧的位置不能大于朦板元素宽度
        if (leftPosition >= maskDom.offsetWidth) leftPosition = maskDom.offsetWidth;


        /*
        * top也是同理
        * */
        if (topPosition <= 0) topPosition = 0;
        if (topPosition >= maskDom.offsetHeight) topPosition = maskDom.offsetHeight;


        // 修改朦板的移动位置
        maskDom.style.left = leftPosition + 'px'
        maskDom.style.top = topPosition + 'px'


        // 修改大图的移动位置
        bigImgDom.style.left = -2 * leftPosition + 'px'
        bigImgDom.style.top = -2 * topPosition + 'px'
      },
    }
  }
</script>

<style lang="less">
  .spec-preview {
    position: relative;
    width: 400px;
    height: 400px;
    border: 1px solid #CDCDCD;

    img {
      width: 100%;
      height: 100%;
    }

    .event {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 998;
      border: 1px solid red;
    }

    .mask {
      width: 50%;
      height: 50%;
      background-color: rgba(0, 255, 0, 0.3);
      position: absolute;
      left: 0;
      top: 0;
      display: none;
    }

    .big {
      width: 100%;
      height: 100%;
      position: absolute;
      top: -1px;
      left: 100%;
      border: 1px solid #aaa;
      overflow: hidden;
      z-index: 998;
      display: none;
      background: white;

      img {
        width: 200%;
        max-width: 200%;
        height: 200%;
        position: absolute;
        left: 0;
        top: 0;
      }
    }

    .event:hover ~ .mask,
    .event:hover ~ .big {
      display: block;
    }
  }
</style>
